//
//  LeveragedTradeViewController.swift
//  Exchange
//
//  Created by rui on 2018/4/18.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class LeveragedTradeViewController: BaseViewController, SelectmangerDelegate {
    
    lazy var viewModel: LeveragedTradeViewModel = LeveragedTradeViewModel()

    
    var sideslipView:SideslipView?
    lazy var leftBtn:CustomBtn = {
        let btn = CustomBtn(style: placeStyle.styleRight)
        btn.photoImageView.image = UIImage(named: "retractLeft")
        btn.photoImageView.themeImage = ThemeManager.ThemeImageKeys.coinRetract
        btn.nameLabel.themeTextColor = ThemeManager.ThemeColorKeys.text1
        btn.addTarget(self, action: #selector(leftBtnAction), for: UIControlEvents.touchUpInside)
        btn.nameLabel.font = UIFont(name: "PingFang-SC-Bold", size: 14)
        btn.bounds = CGRect(x: 0, y: 0, width:100, height: 44)
        return btn
    }()
    
    lazy var leverView:LeveragedTradeView = {
        let view = LeveragedTradeView(dataSource: self)
        
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册监听
        viewModel.peroid = "15\(kText("分"))"
        viewModel.delegate = leverView

        // Do any additional setup after loading the view.
        view.addSubview(leverView)
        leverView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(isiPhoneX() ? -83 : -49)
        }
        
        let orderView = UIView(frame: CGRect(x: 0, y: 0, width: 22, height: 44))
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(pushOrder))
        orderView.addGestureRecognizer(tapGesture)
        
        let icon = UIImageView(image: #imageLiteral(resourceName: "goto_order"))
        icon.contentMode = .center
        icon.frame = orderView.bounds
        orderView.addSubview(icon)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: orderView)
        
        
        self.creatLeftItem()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //获取资产
        if AppInfo.default.isLogin {
            viewModel.archiveInformation()
        }
        if viewModel.coninKidArray.count == 0 {
            self.viewModel.archiveCoinInformation()
        }
        viewModel.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)

        //网络请求结束 没有失败
        APPTransactionPair.default.delegate = self
        if APPTransactionPair.default.isRequestIng == false &&  !APPTransactionPair.default.isRequestFail {
            if viewModel.coinModel.name.count == 0 {
            viewModel.coinModel = APPTransactionPair.default.leverPairModel
            }
            
            leverView.loadData()
            self.changeSubscription()
            
        }
        //网络请求结束 并且 请求失败
        if APPTransactionPair.default.isRequestIng == false && APPTransactionPair.default.isRequestFail {
            APPTransactionPair.default.startPair()
        }
        
        if ThemeManager.default.currentThemeMode() == .day {
            leverView.chartView.style = CHKLineChartStyle.customLight
        }else {
            leverView.chartView.style = CHKLineChartStyle.customDark
        }
        leverView.chartView.reloadData(toPosition: .none, resetData: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.viewModel.clean()
        self.viewModel.removeObserver(self, forKeyPath: "refreshBool", context: nil)

        self.viewModel.changeDepthStates(states: false)
    }
    
    
    /// 修改订阅
    func changeSubscription()  {
        //订阅深度
        viewModel.changeDepthStates(states: true)

        let nameArr = viewModel.coinModel.name.components(separatedBy: "/")
        if  nameArr.count > 1 {
            self.leftBtn.nameLabel.text =  viewModel.coinModel.name
            self.leftBtn.nameLabel.changeLabelTextStyle(title: nameArr.last!, color: (self.leftBtn.nameLabel.textColor)!, font: UIFont(name: "PingFang-SC-Medium", size: 11)!)
        }else {
            self.leftBtn.nameLabel.text = kText("暂无交易对")
        }
        self.archiveRegular()
    }
    
    //获取币种对交易规则
    func archiveRegular()  {
        if viewModel.coinModel.name.count != 0 {
            viewModel.archiveCoinRegular()
        }
    }
    
    
    func selectModel(model: SheetModel) {
        self.viewModel.isMarketBool = ((model as? LeverCapitalModel)?.isMarketBool)!
        viewModel.curretSelectModel = ((model as? LeverCapitalModel)?.model)!
        viewModel.transOrder()
    }
    
    
    /// 买入 卖出
    func openSelect(isBuyBool:Bool)  {
        if !AppInfo.default.isLogin {
            self.navigationController?.pushViewController(LoginViewController(), animated: true)
            return
        }
        if viewModel.coinModel.name.components(separatedBy: "/").count < 2 {
            CYMBShow.showMessage(kText("请选择交易对"))
            return
        }
        let model = LeverTradeModel()
        model.adapterInfo(viewModel: viewModel)
        model.isBuyBool = isBuyBool
        
        SelectActionManger.manager.creatLeverSheet(model: model, dataSource: self)
    }
    
    
    func changeLeverDataModel(model:LeverDataModel) {
        model.buyPrice = viewModel.buyPrice
        model.sellPrice = viewModel.sellPrice
        
    }
    
    @objc func pushOrder() {
        self.navigationController?.customCheckLoginPushViewController(animated: true, { () -> UIViewController in
            let vc = LeverOrderViewController()
            return vc
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            if sideslipView != nil {
                if sideslipView?.isHidden == false {
                    sideslipView?.tableView.reloadData()
                }
            }
        }
    }
    
    
    func creatLeftItem() -> Void {
        leftBtn.frame = CGRect(x: 0, y: 0, width:100, height: 44)
        let item  = UIBarButtonItem(customView: leftBtn)
        leftBtn.photoImageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        leftBtn.nameLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(leftBtn.photoImageView.snp.right).offset(5)
        }
        
        self.navigationItem.leftBarButtonItem = item
        if #available(iOS 11, *) {
        leftBtn.snp.remakeConstraints { (make) in
            make.left.equalTo(item.customView!)
            make.top.equalTo(item.customView!)
            make.height.equalTo(44)
            make.width.equalTo(100)
        }
            leftBtn.setNeedsLayout()
            leftBtn.layoutIfNeeded()
        }
    }
    
    @objc func leftBtnAction() -> Void {
        
        if sideslipView == nil {
            sideslipView = SideslipView()
            
        }
        self.view.endEditing(true)
        sideslipView?.isHidden = false
        sideslipView?.currentPairModel = viewModel.coinModel
        self.viewModel.clean()
        sideslipView?.startSubscription()
        
        sideslipView!.showSides()
        sideslipView?.sideslipBlock = {[weak self] model in
            var regularBool = false
            if model.name != self?.viewModel.coinModel.name {
                //移除之前选择币种对 对应的价格数据
                regularBool = true
            }
            self?.viewModel.coinModel = model
            if regularBool {
                self?.archiveRegular()
                regularBool = false
            }
            self?.viewModel.changeDepthStates(states: true)
            let nameArr = model.name.components(separatedBy: "/")
            if  nameArr.count > 1 {
                self?.leftBtn.nameLabel.text =  model.name
                self?.leftBtn.nameLabel.changeLabelTextStyle(title: nameArr.last!, color: (self?.leftBtn.nameLabel.textColor)!, font: UIFont(name: "PingFang-SC-Medium", size: 11)!)
            }
        }
        sideslipView?.closelipBlock = {[weak self] in
            self?.leverView.loadData()
        }
    }
    
    deinit {
//        self.viewModel.removeObserver(self, forKeyPath: "refreshBool", context: nil)
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension LeveragedTradeViewController:TransactionPairDelegate{
    func requestSuccess() {
        viewModel.coinModel = APPTransactionPair.default.leverPairModel
        self.changeSubscription()
        leverView.loadData()
        if sideslipView != nil {
            if sideslipView?.isHidden == false {
                sideslipView?.updateHeadInformation()
                sideslipView?.currentPairModel = viewModel.coinModel
                sideslipView?.startSubscription()
            }
        }
        
    }
    
}
